/*=====================================================
Critical Links
Auto Configuration Server

Authors:
	Rui Eduardo Gouveia Gil - r-gil@critical-links.com

Date: 2011
Version 0.1
=======================================================*/
DeviceWanWindow = function() {
	this.device;
    this.commands = new Array();

    this.deviceCheckbox = new Ext.form.Checkbox({boxLabel:"Enable remote WAN setup", style:"background:transparent;margin-left:10px;"});
    
    this.deviceWanType = new Ext.form.ComboBox({
        fieldLabel: "Connection Mode",
        width: 140,
        editable: false,
        validationEvent: false,
        validateOnBlur: false,
        msgTarget: "under",
        triggerAction: "all",
        valueField: "id",
        displayField: "text",
        mode: "local",
        listeners:{scope: this},
        store: new Ext.data.ArrayStore({fields: ["id", "text"], data: [["1", "DHCP"], ["2", "Static"], ["3", "PPPoE"]]})
    });

    this.deviceStaticIP = new Ext.form.TextField({fieldLabel:"Ip Address",width:140});
    this.deviceStaticNetmask = new Ext.form.TextField({fieldLabel:"Netmask",width:140});
    this.deviceStaticGateway = new Ext.form.TextField({fieldLabel:"Gateway",width:140});
    this.deviceStaticPrimary = new Ext.form.TextField({fieldLabel:"Primary DNS",width:140});
    this.deviceStaticSecondary = new Ext.form.TextField({fieldLabel:"Secondary DNS",width:140});
    this.formStatic = new Ext.FormPanel({labelWidth: 110, items: [this.deviceStaticIP,this.deviceStaticNetmask,this.deviceStaticGateway,this.deviceStaticPrimary,this.deviceStaticSecondary], border: false, bodyStyle:"background:transparent;"});

    this.devicePPPOEUser = new Ext.form.TextField({fieldLabel:"Username",width:140});
    this.devicePPPOEPass = new Ext.form.TextField({fieldLabel:"Password",width:140,inputType: 'password'});
    this.formPPPOE = new Ext.FormPanel({labelWidth: 110, items: [this.devicePPPOEUser,this.devicePPPOEPass], border: false, bodyStyle:"background:transparent;"});

	this.advanceButton = new Ext.Button({text: "advance...", width: 80, style:"background:transparent; margin-left: 178px;", handler: this.showAdvanceWAN, scope: this});

	this.deviceFieldSet = new Ext.form.FieldSet({labelWidth: 110, border: false, width: 290, items: [this.deviceWanType,this.formStatic,this.formPPPOE,this.advanceButton]});

	DeviceWanWindow.superclass.constructor.call(this, {
        title: "Setup Device WAN",
        iconCls: "wan-device-icon",
        autoHeight: true,
        width: 300,
        resizable: false,
        plain:true,
        modal: true,
        y: 100,
        autoScroll: false,
        closeAction: "hide",

        buttons:[{
            text: "Save",
            handler: this.onSave,
            scope: this
        },{
            text: "Cancel",
            handler: this.hide.createDelegate(this, [])
        }],

        items: [this.deviceCheckbox,this.deviceFieldSet]
    });
    
	this.formPPPOE.hide();
	this.formStatic.hide();
    this.deviceFieldSet.setDisabled(true);
    this.deviceCheckbox.on("check",this.onCheckWan,this);
    this.deviceWanType.on("select",this.onSelectWanType,this);
}

Ext.extend(DeviceWanWindow, Ext.Window, {
    
    show : function(device){
        this.device = device;
        this.formStatic.hide();
        this.formPPPOE.hide();
        this.deviceCheckbox.reset();
        this.devicePPPOEUser.reset();
        this.devicePPPOEPass.reset();
        this.deviceStaticIP.reset();
        this.deviceWanType.setValue("1");
        this.deviceStaticNetmask.reset();
        this.deviceStaticGateway.reset();
        this.deviceStaticPrimary.reset();
        this.deviceStaticSecondary.reset();
        SGui.getDeviceCommands(this.device.id,this.cbDeviceCommands,this);        
        DeviceWanWindow.superclass.show.apply(this, arguments);
    },
    
    onCheckWan : function(check,value) {
    	this.deviceFieldSet.setDisabled(!value);
    },
    
    onSelectWanType : function(combo,record,index )  {
    	if(combo.getValue() == "3") {
    		this.formStatic.hide();
	        this.formPPPOE.show();
    	} else if(combo.getValue() == "2"){
    		this.formStatic.show();
	        this.formPPPOE.hide();
    	} else {
    		this.formStatic.hide();
	        this.formPPPOE.hide();
    	}
    }, 

    showAdvanceWAN : function() {
        if(!this.winAdvWAN){
            this.winAdvWAN = new DeviceWanAdvanceWindow(this.device,this);
        }

        this.winAdvWAN.show(this.deviceWanType.getValue(),this.commands);
    },

    cbDeviceCommands : function(obj,result) {
     	if(result) {
    		obj.commands = new Array();
    		if(result instanceof Array) {
    			for(var i=0; i<result.length; i++) {
    				obj.commands.push(new Command(result[i]));
    			}
    		} else {
    			obj.commands.push(new Command(result));
    		}

			obj.deviceCheckbox.setValue(true);
    		obj.deviceFieldSet.setDisabled(false);
    		
    		if(obj.commands.length) {
    			if(obj.commands[0].action == "enableInternetDhcp") {
		    		obj.formStatic.hide();
			        obj.formPPPOE.hide();
			        obj.deviceWanType.setValue("1");
    			} else if(obj.commands[0].action == "enableInternetStatic") {
		    		obj.formStatic.show();
			        obj.formPPPOE.hide();
			        obj.deviceStaticIP.setValue(obj.commands[0].args[0]);
			        obj.deviceStaticNetmask.setValue(obj.commands[0].args[1]);
			        obj.deviceStaticGateway.setValue(obj.commands[0].args[2]);
			        obj.deviceStaticPrimary.setValue(obj.commands[0].args[3]);
			        if(obj.commands[0].args.length > 4)
			        	obj.deviceStaticSecondary.setValue(obj.commands[0].args[4]);
			        obj.deviceWanType.setValue("2");
    			} else if(obj.commands[0].action == "enableInternetPppoe") {
		    		obj.formStatic.hide();
			        obj.formPPPOE.show();					
			        obj.devicePPPOEUser.setValue(obj.commands[0].args[0]);
			        obj.devicePPPOEPass.setValue(obj.commands[0].args[1]);
			        obj.deviceWanType.setValue("3");
    			}
    		}
    	} else {   
			obj.formPPPOE.hide();
			obj.formStatic.hide();
			obj.deviceCheckbox.setValue(false);
    		obj.deviceFieldSet.setDisabled(true);
    	}
    },
    
    onSave : function(){
    	var valid=true;
    	
    	if(this.deviceCheckbox.getValue()) {
    		var newCommands = new Array();

    		if(this.deviceWanType.getValue() == "3") {
    			if(this.devicePPPOEUser.getValue().length == 0) {
					this.devicePPPOEUser.markInvalid("Invalid username!");
					valid=false;
				}
	
				if(this.devicePPPOEPass.getValue().length == 0) {
					this.devicePPPOEPass.markInvalid("Invalid password!");
					valid=false;
				}
	
				if(valid) {
		    		this.el.mask("Saving wan setup...", "x-mask-loading");
					newCommands.push("enableInternetPppoe "+this.devicePPPOEUser.getValue()+" "+this.devicePPPOEPass.getValue());
					for(var i=0; i<this.commands.length; i++) {
						if(this.commands[i].action == "setInternetIpAddress") {
							newCommands.push("setInternetIpAddress "+this.commands[i].args[0]);
			    		}  			
						else if(this.commands[i].action == "setInternetGateway") {
							newCommands.push("setInternetGateway "+this.commands[i].args[0]);
			    		}  			
						else if(this.commands[i].action == "setInternetDNS") {
							if(this.commands[i].args.length == 1)
								newCommands.push("setInternetDNS "+this.commands[i].args[0]);
							else
								newCommands.push("setInternetDNS "+this.commands[i].args[0]+" "+this.commands[i].args[1]);
			    		}  			
						else if(this.commands[i].action == "setInternetVlanValue") {
							if(this.commands[i].args.length == 0)
								newCommands.push("setInternetVlanValue");
							else
								newCommands.push("setInternetVlanValue "+this.commands[i].args[0]);
			    		}  			
						else if(this.commands[i].action == "setInternetMTUValue") {
							newCommands.push("setInternetMTUValue "+this.commands[i].args[0]);
			    		}  			
					}
				}
	    	} else if(this.deviceWanType.getValue() == "2"){	    		
				if(this.deviceStaticIP.getValue().length == 0 || verifyIP(this.deviceStaticIP.getValue())== false) {
					this.deviceStaticIP.markInvalid("Invalid IP Address!");
					valid=false;
				}
	
				if(this.deviceStaticNetmask.getValue().length == 0 || verifyNetmask(this.deviceStaticNetmask.getValue())== false) {
					this.deviceStaticNetmask.markInvalid("Invalid Netmask!");
					valid=false;
				}
	
				if(this.deviceStaticGateway.getValue().length == 0 || verifyIP(this.deviceStaticGateway.getValue())== false) {
					this.deviceStaticGateway.markInvalid("Invalid Gateway!");
					valid=false;
				}
	
				if(this.deviceStaticPrimary.getValue().length == 0 || verifyIP(this.deviceStaticPrimary.getValue())== false) {
					this.deviceStaticPrimary.markInvalid("Invalid Primary DNS!");
					valid=false;
				}
	
				if(this.deviceStaticSecondary.getValue().length != 0 && verifyIP(this.deviceStaticSecondary.getValue())== false) {
					this.deviceStaticSecondary.markInvalid("Invalid Secondary DNS!");
					valid=false;
				}
	    		
				if(valid) {
					var cmd = "enableInternetStatic "+this.deviceStaticIP.getValue()+" "+this.deviceStaticNetmask.getValue()+" "+this.deviceStaticGateway.getValue()+" "+this.deviceStaticPrimary.getValue();
					if(this.deviceStaticSecondary.getValue().length != 0) {
						cmd += " " + this.deviceStaticSecondary.getValue();
					}
					
		    		newCommands.push(cmd);
					
					for(var i=0; i<this.commands.length; i++) {
						if(this.commands[i].action == "setInternetMTUValue") {
							newCommands.push("setInternetMTUValue "+this.commands[i].args[0]);
							break;
			    		}  			
					}
				}					    		
	    	} else {
	    		newCommands.push("enableInternetDhcp");
				for(var i=0; i<this.commands.length; i++) {
					if(this.commands[i].action == "setInternetMTUValue") {
						newCommands.push("setInternetMTUValue "+this.commands[i].args[0]);
						break;
		    		}  			
				}					    		
	    	}    		

			if(valid) {
    			this.el.mask("Saving wan setup...", "x-mask-loading");
    			SGui.setDeviceCommands(this.device.id,newCommands,this.cbAddCommand,this);
			}
    	} else {
	    	this.el.mask("Saving wan setup...", "x-mask-loading");
			SGui.removeDeviceCommands(this.device.id,this.cbAddCommand,this);
		}
    },  

	cbAddCommand : function(obj,result) {
    	if(result instanceof Array && result[0] == "-1") {
    		Ext.MessageBox.show({title: "Error", msg: "Invalid Configuration.", buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
    	} else {
	   		obj.el.unmask();
		    obj.hide();
			obj.fireEvent("savewan");
    	}
	},
	
	setAdvanceCommands : function(commands) {
		this.commands = commands;
	}
});
